


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Futures (Scala) &mdash; Akka Documentation</title>
    
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/prettify.css" type="text/css" />
    <link rel="stylesheet" href="../_static/base.css" type="text/css" />
    <link rel="stylesheet" href="../_static/docs.css" type="text/css" />
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Exo:300,400,600,700" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.0.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/toc.js"></script>
    <script type="text/javascript" src="../_static/prettify.js"></script>
    <script type="text/javascript" src="../_static/highlightCode.js"></script>
    <script type="text/javascript" src="../_static/effects.core.js"></script>
    <script type="text/javascript" src="../_static/effects.highlight.js"></script>
    <script type="text/javascript" src="../_static/scrollTo.js"></script>
    <script type="text/javascript" src="../_static/contentsFix.js"></script>
    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="top" title="Akka Documentation" href="../index.html" />
    <link rel="up" title="Scala API" href="index.html" />
    <link rel="next" title="Dataflow Concurrency (Scala)" href="dataflow.html" />
    <link rel="prev" title="Scheduler (Scala)" href="scheduler.html" /> 
  </head>
  <body>
  <div class="navbar">
    <div class="navbar-inner">
      <div class="container">
        <div class="navbar-logo">
          <a href="http://akka.io"><img src="../_static/logo-small.png" /></a>
        </div>    
        <ul class="nav">
          <li><a href="http://akka.io/docs">Documentation</a></li>
          <li><a href="http://akka.io/downloads">Download</a></li>
          <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>
          <li><a href="http://github.com/akka/akka">Code</a></li>           
          <li><a href="http://typesafe.com/products/typesafe-subscription">Commerical Support</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="main">
    <div class="container">
      <div class="page-title">Futures (Scala)</div><div class="pdf-link"><a href="http://akka.io/docs/akka/2.0.1/Akka.pdf"><img src="../_static/pdf-icon.png" style="height: 40px;" /></a></div></div>
    <div class="main-container">
      <div class="container">
        <div class="row">
          <div class="span12">
            <ul class="breadcrumb">           
              <li>
                 <span class="divider">|</span> <a href="dataflow.html">Dataflow Concurrency (Scala)</a> <span class="divider">»</span>
              </li>
              <li>
                <a href="../index.html">Contents</a>
              </li>
              <li>
                <span class="divider">«</span> <a href="scheduler.html">Scheduler (Scala)</a> <span class="divider">|</span>
              </li>
              <li>
                Version 2.0.1
              </li>
            </ul>         
          </div>
        </div>
        <div class="row">
          <div class="span9">
            
  <div class="section" id="futures-scala">
<span id="id1"></span><h1>Futures (Scala)</h1>
<div class="section" id="introduction">
<h2>Introduction</h2>
<p>In Akka, a <a class="reference external" href="http://en.wikipedia.org/wiki/Futures_and_promises">Future</a> is a data structure used to
retrieve the result of some concurrent operation. This operation is usually performed by an <tt class="docutils literal"><span class="pre">Actor</span></tt>
or by the <tt class="docutils literal"><span class="pre">Dispatcher</span></tt> directly. This result can be accessed synchronously (blocking) or asynchronously (non-blocking).</p>
</div>
<div class="section" id="execution-contexts">
<h2>Execution Contexts</h2>
<p>In order to execute callbacks and operations, Futures need something called an <tt class="docutils literal"><span class="pre">ExecutionContext</span></tt>,
which is very similar to a <tt class="docutils literal"><span class="pre">java.util.concurrent.Executor</span></tt>. if you have an <tt class="docutils literal"><span class="pre">ActorSystem</span></tt> in scope,
it will use its default dispatcher as the <tt class="docutils literal"><span class="pre">ExecutionContext</span></tt>, or you can use the factory methods provided
by the <tt class="docutils literal"><span class="pre">ExecutionContext</span></tt> companion object to wrap <tt class="docutils literal"><span class="pre">Executors</span></tt> and <tt class="docutils literal"><span class="pre">ExecutorServices</span></tt>, or even create your own.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.dispatch.</span><span class="o">{</span> <span class="nc">ExecutionContext</span><span class="o">,</span> <span class="nc">Promise</span> <span class="o">}</span>

<span class="k">implicit</span> <span class="k">val</span> <span class="n">ec</span> <span class="k">=</span> <span class="nc">ExecutionContext</span><span class="o">.</span><span class="n">fromExecutorService</span><span class="o">(</span><span class="n">yourExecutorServiceGoesHere</span><span class="o">)</span>

<span class="c1">// Do stuff with your brand new shiny ExecutionContext</span>
<span class="k">val</span> <span class="n">f</span> <span class="k">=</span> <span class="nc">Promise</span><span class="o">.</span><span class="n">successful</span><span class="o">(</span><span class="s">&quot;foo&quot;</span><span class="o">)</span>

<span class="c1">// Then shut your ExecutionContext down at some</span>
<span class="c1">// appropriate place in your program/application</span>
<span class="n">ec</span><span class="o">.</span><span class="n">shutdown</span><span class="o">()</span>
</pre></div>
</div>
</div>
<div class="section" id="use-with-actors">
<h2>Use With Actors</h2>
<p>There are generally two ways of getting a reply from an <tt class="docutils literal"><span class="pre">Actor</span></tt>: the first is by a sent message (<tt class="docutils literal"><span class="pre">actor</span> <span class="pre">!</span> <span class="pre">msg</span></tt>),
which only works if the original sender was an <tt class="docutils literal"><span class="pre">Actor</span></tt>) and the second is through a <tt class="docutils literal"><span class="pre">Future</span></tt>.</p>
<p>Using an <tt class="docutils literal"><span class="pre">Actor</span></tt>&#8216;s <tt class="docutils literal"><span class="pre">?</span></tt> method to send a message will return a Future. To wait for and retrieve the actual result the simplest method is:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.dispatch.Await</span>
<span class="k">import</span> <span class="nn">akka.pattern.ask</span>
<span class="k">import</span> <span class="nn">akka.util.Timeout</span>
<span class="k">import</span> <span class="nn">akka.util.duration._</span>

<span class="k">implicit</span> <span class="k">val</span> <span class="n">timeout</span> <span class="k">=</span> <span class="nc">Timeout</span><span class="o">(</span><span class="mi">5</span> <span class="n">seconds</span><span class="o">)</span>
<span class="k">val</span> <span class="n">future</span> <span class="k">=</span> <span class="n">actor</span> <span class="o">?</span> <span class="n">msg</span> <span class="c1">// enabled by the “ask” import</span>
<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">future</span><span class="o">,</span> <span class="n">timeout</span><span class="o">.</span><span class="n">duration</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span>
</pre></div>
</div>
<p>This will cause the current thread to block and wait for the <tt class="docutils literal"><span class="pre">Actor</span></tt> to &#8216;complete&#8217; the <tt class="docutils literal"><span class="pre">Future</span></tt> with it&#8217;s reply.
Blocking is discouraged though as it will cause performance problems.
The blocking operations are located in <tt class="docutils literal"><span class="pre">Await.result</span></tt> and <tt class="docutils literal"><span class="pre">Await.ready</span></tt> to make it easy to spot where blocking occurs.
Alternatives to blocking are discussed further within this documentation. Also note that the <tt class="docutils literal"><span class="pre">Future</span></tt> returned by
an <tt class="docutils literal"><span class="pre">Actor</span></tt> is a <tt class="docutils literal"><span class="pre">Future[Any]</span></tt> since an <tt class="docutils literal"><span class="pre">Actor</span></tt> is dynamic. That is why the <tt class="docutils literal"><span class="pre">asInstanceOf</span></tt> is used in the above sample.
When using non-blocking it is better to use the <tt class="docutils literal"><span class="pre">mapTo</span></tt> method to safely try to cast a <tt class="docutils literal"><span class="pre">Future</span></tt> to an expected type:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.dispatch.Future</span>
<span class="k">import</span> <span class="nn">akka.pattern.ask</span>

<span class="k">val</span> <span class="n">future</span><span class="k">:</span> <span class="kt">Future</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span> <span class="k">=</span> <span class="n">ask</span><span class="o">(</span><span class="n">actor</span><span class="o">,</span> <span class="n">msg</span><span class="o">).</span><span class="n">mapTo</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">mapTo</span></tt> method will return a new <tt class="docutils literal"><span class="pre">Future</span></tt> that contains the result if the cast was successful,
or a <tt class="docutils literal"><span class="pre">ClassCastException</span></tt> if not. Handling <tt class="docutils literal"><span class="pre">Exception</span></tt>s will be discussed further within this documentation.</p>
</div>
<div class="section" id="use-directly">
<h2>Use Directly</h2>
<p>A common use case within Akka is to have some computation performed concurrently without needing the extra utility of an <tt class="docutils literal"><span class="pre">Actor</span></tt>.
If you find yourself creating a pool of <tt class="docutils literal"><span class="pre">Actor</span></tt>s for the sole reason of performing a calculation in parallel,
there is an easier (and faster) way:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.dispatch.Await</span>
<span class="k">import</span> <span class="nn">akka.dispatch.Future</span>
<span class="k">import</span> <span class="nn">akka.util.duration._</span>

<span class="k">val</span> <span class="n">future</span> <span class="k">=</span> <span class="nc">Future</span> <span class="o">{</span>
  <span class="s">&quot;Hello&quot;</span> <span class="o">+</span> <span class="s">&quot;World&quot;</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">future</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">)</span>
</pre></div>
</div>
<p>In the above code the block passed to <tt class="docutils literal"><span class="pre">Future</span></tt> will be executed by the default <tt class="docutils literal"><span class="pre">Dispatcher</span></tt>,
with the return value of the block used to complete the <tt class="docutils literal"><span class="pre">Future</span></tt> (in this case, the result would be the string: &#8220;HelloWorld&#8221;).
Unlike a <tt class="docutils literal"><span class="pre">Future</span></tt> that is returned from an <tt class="docutils literal"><span class="pre">Actor</span></tt>, this <tt class="docutils literal"><span class="pre">Future</span></tt> is properly typed,
and we also avoid the overhead of managing an <tt class="docutils literal"><span class="pre">Actor</span></tt>.</p>
<p>You can also create already completed Futures using the <tt class="docutils literal"><span class="pre">Promise</span></tt> companion, which can be either successes:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">future</span> <span class="k">=</span> <span class="nc">Promise</span><span class="o">.</span><span class="n">successful</span><span class="o">(</span><span class="s">&quot;Yay!&quot;</span><span class="o">)</span>
</pre></div>
</div>
<p>Or failures:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">otherFuture</span> <span class="k">=</span> <span class="nc">Promise</span><span class="o">.</span><span class="n">failed</span><span class="o">[</span><span class="kt">String</span><span class="o">](</span><span class="k">new</span> <span class="nc">IllegalArgumentException</span><span class="o">(</span><span class="s">&quot;Bang!&quot;</span><span class="o">))</span>
</pre></div>
</div>
</div>
<div class="section" id="functional-futures">
<h2>Functional Futures</h2>
<p>Akka&#8217;s <tt class="docutils literal"><span class="pre">Future</span></tt> has several monadic methods that are very similar to the ones used by Scala&#8217;s collections.
These allow you to create &#8216;pipelines&#8217; or &#8216;streams&#8217; that the result will travel through.</p>
<div class="section" id="future-is-a-monad">
<h3>Future is a Monad</h3>
<p>The first method for working with <tt class="docutils literal"><span class="pre">Future</span></tt> functionally is <tt class="docutils literal"><span class="pre">map</span></tt>. This method takes a <tt class="docutils literal"><span class="pre">Function</span></tt>
which performs some operation on the result of the <tt class="docutils literal"><span class="pre">Future</span></tt>, and returning a new result.
The return value of the <tt class="docutils literal"><span class="pre">map</span></tt> method is another <tt class="docutils literal"><span class="pre">Future</span></tt> that will contain the new result:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">f1</span> <span class="k">=</span> <span class="nc">Future</span> <span class="o">{</span>
  <span class="s">&quot;Hello&quot;</span> <span class="o">+</span> <span class="s">&quot;World&quot;</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">f2</span> <span class="k">=</span> <span class="n">f1</span> <span class="n">map</span> <span class="o">{</span> <span class="n">x</span> <span class="k">⇒</span>
  <span class="n">x</span><span class="o">.</span><span class="n">length</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">f2</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">)</span>
<span class="n">result</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">10</span><span class="o">)</span>
<span class="n">f1</span><span class="o">.</span><span class="n">value</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="nc">Some</span><span class="o">(</span><span class="nc">Right</span><span class="o">(</span><span class="s">&quot;HelloWorld&quot;</span><span class="o">)))</span>
</pre></div>
</div>
<p>In this example we are joining two strings together within a <tt class="docutils literal"><span class="pre">Future</span></tt>. Instead of waiting for this to complete,
we apply our function that calculates the length of the string using the <tt class="docutils literal"><span class="pre">map</span></tt> method.
Now we have a second <tt class="docutils literal"><span class="pre">Future</span></tt> that will eventually contain an <tt class="docutils literal"><span class="pre">Int</span></tt>.
When our original <tt class="docutils literal"><span class="pre">Future</span></tt> completes, it will also apply our function and complete the second <tt class="docutils literal"><span class="pre">Future</span></tt> with its result.
When we finally get the result, it will contain the number 10. Our original <tt class="docutils literal"><span class="pre">Future</span></tt> still contains the
string &#8220;HelloWorld&#8221; and is unaffected by the <tt class="docutils literal"><span class="pre">map</span></tt>.</p>
<p>The <tt class="docutils literal"><span class="pre">map</span></tt> method is fine if we are modifying a single <tt class="docutils literal"><span class="pre">Future</span></tt>,
but if 2 or more <tt class="docutils literal"><span class="pre">Future</span></tt>s are involved <tt class="docutils literal"><span class="pre">map</span></tt> will not allow you to combine them together:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">f1</span> <span class="k">=</span> <span class="nc">Future</span> <span class="o">{</span>
  <span class="s">&quot;Hello&quot;</span> <span class="o">+</span> <span class="s">&quot;World&quot;</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">f2</span> <span class="k">=</span> <span class="nc">Promise</span><span class="o">.</span><span class="n">successful</span><span class="o">(</span><span class="mi">3</span><span class="o">)</span>
<span class="k">val</span> <span class="n">f3</span> <span class="k">=</span> <span class="n">f1</span> <span class="n">map</span> <span class="o">{</span> <span class="n">x</span> <span class="k">⇒</span>
  <span class="n">f2</span> <span class="n">map</span> <span class="o">{</span> <span class="n">y</span> <span class="k">⇒</span>
    <span class="n">x</span><span class="o">.</span><span class="n">length</span> <span class="o">*</span> <span class="n">y</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">f3</span></tt> is a <tt class="docutils literal"><span class="pre">Future[Future[Int]]</span></tt> instead of the desired <tt class="docutils literal"><span class="pre">Future[Int]</span></tt>. Instead, the <tt class="docutils literal"><span class="pre">flatMap</span></tt> method should be used:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">f1</span> <span class="k">=</span> <span class="nc">Future</span> <span class="o">{</span>
  <span class="s">&quot;Hello&quot;</span> <span class="o">+</span> <span class="s">&quot;World&quot;</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">f2</span> <span class="k">=</span> <span class="nc">Promise</span><span class="o">.</span><span class="n">successful</span><span class="o">(</span><span class="mi">3</span><span class="o">)</span>
<span class="k">val</span> <span class="n">f3</span> <span class="k">=</span> <span class="n">f1</span> <span class="n">flatMap</span> <span class="o">{</span> <span class="n">x</span> <span class="k">⇒</span>
  <span class="n">f2</span> <span class="n">map</span> <span class="o">{</span> <span class="n">y</span> <span class="k">⇒</span>
    <span class="n">x</span><span class="o">.</span><span class="n">length</span> <span class="o">*</span> <span class="n">y</span>
  <span class="o">}</span>
<span class="o">}</span>
<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">f3</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">)</span>
<span class="n">result</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">30</span><span class="o">)</span>
</pre></div>
</div>
<p>Composing futures using nested combinators it can sometimes become quite complicated and hard read, in these cases using Scala&#8217;s
&#8216;for comprehensions&#8217; usually yields more readable code. See next section for examples.</p>
<p>If you need to do conditional propagation, you can use <tt class="docutils literal"><span class="pre">filter</span></tt>:</p>
<div class="highlight-scala"><pre>val future1 = Promise.successful(4)
val future2 = future1.filter(_ % 2 == 0)
val result = Await.result(future2, 1 second)
result must be(4)

val failedFilter = future1.filter(_ % 2 == 1).recover {
  case m: MatchError ⇒ 0 //When filter fails, it will have a MatchError
}
val result2 = Await.result(failedFilter, 1 second)
result2 must be(0) //Can only be 0 when there was a MatchError
</pre>
</div>
</div>
<div class="section" id="for-comprehensions">
<h3>For Comprehensions</h3>
<p>Since <tt class="docutils literal"><span class="pre">Future</span></tt> has a <tt class="docutils literal"><span class="pre">map</span></tt>, <tt class="docutils literal"><span class="pre">filter</span></tt> and <tt class="docutils literal"><span class="pre">flatMap</span></tt> method it can be easily used in a &#8216;for comprehension&#8217;:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">f</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
  <span class="n">a</span> <span class="k">←</span> <span class="nc">Future</span><span class="o">(</span><span class="mi">10</span> <span class="o">/</span> <span class="mi">2</span><span class="o">)</span> <span class="c1">// 10 / 2 = 5</span>
  <span class="n">b</span> <span class="k">←</span> <span class="nc">Future</span><span class="o">(</span><span class="n">a</span> <span class="o">+</span> <span class="mi">1</span><span class="o">)</span> <span class="c1">//  5 + 1 = 6</span>
  <span class="n">c</span> <span class="k">←</span> <span class="nc">Future</span><span class="o">(</span><span class="n">a</span> <span class="o">-</span> <span class="mi">1</span><span class="o">)</span> <span class="c1">//  5 - 1 = 4</span>
  <span class="k">if</span> <span class="n">c</span> <span class="o">&gt;</span> <span class="mi">3</span> <span class="c1">// Future.filter</span>
<span class="o">}</span> <span class="k">yield</span> <span class="n">b</span> <span class="o">*</span> <span class="n">c</span> <span class="c1">//  6 * 4 = 24</span>

<span class="c1">// Note that the execution of futures a, b, and c</span>
<span class="c1">// are not done in parallel.</span>

<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">f</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">)</span>
<span class="n">result</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">24</span><span class="o">)</span>
</pre></div>
</div>
<p>Something to keep in mind when doing this is even though it looks like parts of the above example can run in parallel,
each step of the for comprehension is run sequentially. This will happen on separate threads for each step but
there isn&#8217;t much benefit over running the calculations all within a single <tt class="docutils literal"><span class="pre">Future</span></tt>.
The real benefit comes when the <tt class="docutils literal"><span class="pre">Future</span></tt>s are created first, and then combining them together.</p>
</div>
<div class="section" id="composing-futures">
<h3>Composing Futures</h3>
<p>The example for comprehension above is an example of composing <tt class="docutils literal"><span class="pre">Future</span></tt>s.
A common use case for this is combining the replies of several <tt class="docutils literal"><span class="pre">Actor</span></tt>s into a single calculation
without resorting to calling <tt class="docutils literal"><span class="pre">Await.result</span></tt> or <tt class="docutils literal"><span class="pre">Await.ready</span></tt> to block for each result.
First an example of using <tt class="docutils literal"><span class="pre">Await.result</span></tt>:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">f1</span> <span class="k">=</span> <span class="n">ask</span><span class="o">(</span><span class="n">actor1</span><span class="o">,</span> <span class="n">msg1</span><span class="o">)</span>
<span class="k">val</span> <span class="n">f2</span> <span class="k">=</span> <span class="n">ask</span><span class="o">(</span><span class="n">actor2</span><span class="o">,</span> <span class="n">msg2</span><span class="o">)</span>

<span class="k">val</span> <span class="n">a</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">f1</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
<span class="k">val</span> <span class="n">b</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">f2</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>

<span class="k">val</span> <span class="n">f3</span> <span class="k">=</span> <span class="n">ask</span><span class="o">(</span><span class="n">actor3</span><span class="o">,</span> <span class="o">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="o">))</span>

<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">f3</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
</pre></div>
</div>
<p>Here we wait for the results from the first 2 <tt class="docutils literal"><span class="pre">Actor</span></tt>s before sending that result to the third <tt class="docutils literal"><span class="pre">Actor</span></tt>.
We called <tt class="docutils literal"><span class="pre">Await.result</span></tt> 3 times, which caused our little program to block 3 times before getting our final result.
Now compare that to this example:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">f1</span> <span class="k">=</span> <span class="n">ask</span><span class="o">(</span><span class="n">actor1</span><span class="o">,</span> <span class="n">msg1</span><span class="o">)</span>
<span class="k">val</span> <span class="n">f2</span> <span class="k">=</span> <span class="n">ask</span><span class="o">(</span><span class="n">actor2</span><span class="o">,</span> <span class="n">msg2</span><span class="o">)</span>

<span class="k">val</span> <span class="n">f3</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
  <span class="n">a</span> <span class="k">←</span> <span class="n">f1</span><span class="o">.</span><span class="n">mapTo</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
  <span class="n">b</span> <span class="k">←</span> <span class="n">f2</span><span class="o">.</span><span class="n">mapTo</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
  <span class="n">c</span> <span class="k">←</span> <span class="n">ask</span><span class="o">(</span><span class="n">actor3</span><span class="o">,</span> <span class="o">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="o">)).</span><span class="n">mapTo</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
<span class="o">}</span> <span class="k">yield</span> <span class="n">c</span>

<span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">f3</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
</pre></div>
</div>
<p>Here we have 2 actors processing a single message each. Once the 2 results are available
(note that we don&#8217;t block to get these results!), they are being added together and sent to a third <tt class="docutils literal"><span class="pre">Actor</span></tt>,
which replies with a string, which we assign to &#8216;result&#8217;.</p>
<p>This is fine when dealing with a known amount of Actors, but can grow unwieldy if we have more then a handful.
The <tt class="docutils literal"><span class="pre">sequence</span></tt> and <tt class="docutils literal"><span class="pre">traverse</span></tt> helper methods can make it easier to handle more complex use cases.
Both of these methods are ways of turning, for a subclass <tt class="docutils literal"><span class="pre">T</span></tt> of <tt class="docutils literal"><span class="pre">Traversable</span></tt>, <tt class="docutils literal"><span class="pre">T[Future[A]]</span></tt> into a <tt class="docutils literal"><span class="pre">Future[T[A]]</span></tt>.
For example:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="c1">// oddActor returns odd numbers sequentially from 1 as a List[Future[Int]]</span>
<span class="k">val</span> <span class="n">listOfFutures</span> <span class="k">=</span> <span class="nc">List</span><span class="o">.</span><span class="n">fill</span><span class="o">(</span><span class="mi">100</span><span class="o">)(</span><span class="n">akka</span><span class="o">.</span><span class="n">pattern</span><span class="o">.</span><span class="n">ask</span><span class="o">(</span><span class="n">oddActor</span><span class="o">,</span> <span class="nc">GetNext</span><span class="o">).</span><span class="n">mapTo</span><span class="o">[</span><span class="kt">Int</span><span class="o">])</span>

<span class="c1">// now we have a Future[List[Int]]</span>
<span class="k">val</span> <span class="n">futureList</span> <span class="k">=</span> <span class="nc">Future</span><span class="o">.</span><span class="n">sequence</span><span class="o">(</span><span class="n">listOfFutures</span><span class="o">)</span>

<span class="c1">// Find the sum of the odd numbers</span>
<span class="k">val</span> <span class="n">oddSum</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">futureList</span><span class="o">.</span><span class="n">map</span><span class="o">(</span><span class="n">_</span><span class="o">.</span><span class="n">sum</span><span class="o">),</span> <span class="mi">1</span> <span class="n">second</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
<span class="n">oddSum</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">10000</span><span class="o">)</span>
</pre></div>
</div>
<p>To better explain what happened in the example, <tt class="docutils literal"><span class="pre">Future.sequence</span></tt> is taking the <tt class="docutils literal"><span class="pre">List[Future[Int]]</span></tt>
and turning it into a <tt class="docutils literal"><span class="pre">Future[List[Int]]</span></tt>. We can then use <tt class="docutils literal"><span class="pre">map</span></tt> to work with the <tt class="docutils literal"><span class="pre">List[Int]</span></tt> directly,
and we find the sum of the <tt class="docutils literal"><span class="pre">List</span></tt>.</p>
<p>The <tt class="docutils literal"><span class="pre">traverse</span></tt> method is similar to <tt class="docutils literal"><span class="pre">sequence</span></tt>, but it takes a <tt class="docutils literal"><span class="pre">T[A]</span></tt> and a function <tt class="docutils literal"><span class="pre">A</span> <span class="pre">=&gt;</span> <span class="pre">Future[B]</span></tt> to return a <tt class="docutils literal"><span class="pre">Future[T[B]]</span></tt>,
where <tt class="docutils literal"><span class="pre">T</span></tt> is again a subclass of Traversable. For example, to use <tt class="docutils literal"><span class="pre">traverse</span></tt> to sum the first 100 odd numbers:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">futureList</span> <span class="k">=</span> <span class="nc">Future</span><span class="o">.</span><span class="n">traverse</span><span class="o">((</span><span class="mi">1</span> <span class="n">to</span> <span class="mi">100</span><span class="o">).</span><span class="n">toList</span><span class="o">)(</span><span class="n">x</span> <span class="k">⇒</span> <span class="nc">Future</span><span class="o">(</span><span class="n">x</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">-</span> <span class="mi">1</span><span class="o">))</span>
<span class="k">val</span> <span class="n">oddSum</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">futureList</span><span class="o">.</span><span class="n">map</span><span class="o">(</span><span class="n">_</span><span class="o">.</span><span class="n">sum</span><span class="o">),</span> <span class="mi">1</span> <span class="n">second</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
<span class="n">oddSum</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">10000</span><span class="o">)</span>
</pre></div>
</div>
<p>This is the same result as this example:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">futureList</span> <span class="k">=</span> <span class="nc">Future</span><span class="o">.</span><span class="n">sequence</span><span class="o">((</span><span class="mi">1</span> <span class="n">to</span> <span class="mi">100</span><span class="o">).</span><span class="n">toList</span><span class="o">.</span><span class="n">map</span><span class="o">(</span><span class="n">x</span> <span class="k">⇒</span> <span class="nc">Future</span><span class="o">(</span><span class="n">x</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">-</span> <span class="mi">1</span><span class="o">)))</span>
<span class="k">val</span> <span class="n">oddSum</span> <span class="k">=</span> <span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">futureList</span><span class="o">.</span><span class="n">map</span><span class="o">(</span><span class="n">_</span><span class="o">.</span><span class="n">sum</span><span class="o">),</span> <span class="mi">1</span> <span class="n">second</span><span class="o">).</span><span class="n">asInstanceOf</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span>
<span class="n">oddSum</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">10000</span><span class="o">)</span>
</pre></div>
</div>
<p>But it may be faster to use <tt class="docutils literal"><span class="pre">traverse</span></tt> as it doesn&#8217;t have to create an intermediate <tt class="docutils literal"><span class="pre">List[Future[Int]]</span></tt>.</p>
<p>Then there&#8217;s a method that&#8217;s called <tt class="docutils literal"><span class="pre">fold</span></tt> that takes a start-value, a sequence of <tt class="docutils literal"><span class="pre">Future</span></tt>s and a function
from the type of the start-value and the type of the futures and returns something with the same type as the start-value,
and then applies the function to all elements in the sequence of futures, asynchronously,
the execution will start when the last of the Futures is completed.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">futures</span> <span class="k">=</span> <span class="k">for</span> <span class="o">(</span><span class="n">i</span> <span class="k">←</span> <span class="mi">1</span> <span class="n">to</span> <span class="mi">1000</span><span class="o">)</span> <span class="k">yield</span> <span class="nc">Future</span><span class="o">(</span><span class="n">i</span> <span class="o">*</span> <span class="mi">2</span><span class="o">)</span> <span class="c1">// Create a sequence of Futures</span>
<span class="k">val</span> <span class="n">futureSum</span> <span class="k">=</span> <span class="nc">Future</span><span class="o">.</span><span class="n">fold</span><span class="o">(</span><span class="n">futures</span><span class="o">)(</span><span class="mi">0</span><span class="o">)(</span><span class="k">_</span> <span class="o">+</span> <span class="n">_</span><span class="o">)</span>
<span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">futureSum</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">)</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">1001000</span><span class="o">)</span>
</pre></div>
</div>
<p>That&#8217;s all it takes!</p>
<p>If the sequence passed to <tt class="docutils literal"><span class="pre">fold</span></tt> is empty, it will return the start-value, in the case above, that will be 0.
In some cases you don&#8217;t have a start-value and you&#8217;re able to use the value of the first completing Future in the sequence
as the start-value, you can use <tt class="docutils literal"><span class="pre">reduce</span></tt>, it works like this:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">futures</span> <span class="k">=</span> <span class="k">for</span> <span class="o">(</span><span class="n">i</span> <span class="k">←</span> <span class="mi">1</span> <span class="n">to</span> <span class="mi">1000</span><span class="o">)</span> <span class="k">yield</span> <span class="nc">Future</span><span class="o">(</span><span class="n">i</span> <span class="o">*</span> <span class="mi">2</span><span class="o">)</span> <span class="c1">// Create a sequence of Futures</span>
<span class="k">val</span> <span class="n">futureSum</span> <span class="k">=</span> <span class="nc">Future</span><span class="o">.</span><span class="n">reduce</span><span class="o">(</span><span class="n">futures</span><span class="o">)(</span><span class="k">_</span> <span class="o">+</span> <span class="n">_</span><span class="o">)</span>
<span class="nc">Await</span><span class="o">.</span><span class="n">result</span><span class="o">(</span><span class="n">futureSum</span><span class="o">,</span> <span class="mi">1</span> <span class="n">second</span><span class="o">)</span> <span class="n">must</span> <span class="n">be</span><span class="o">(</span><span class="mi">1001000</span><span class="o">)</span>
</pre></div>
</div>
<p>Same as with <tt class="docutils literal"><span class="pre">fold</span></tt>, the execution will be done asynchronously when the last of the Future is completed,
you can also parallelize it by chunking your futures into sub-sequences and reduce them, and then reduce the reduced results again.</p>
</div>
</div>
<div class="section" id="callbacks">
<h2>Callbacks</h2>
<p>Sometimes you just want to listen to a <tt class="docutils literal"><span class="pre">Future</span></tt> being completed, and react to that not by creating a new Future, but by side-effecting.
For this Akka supports <tt class="docutils literal"><span class="pre">onComplete</span></tt>, <tt class="docutils literal"><span class="pre">onSuccess</span></tt> and <tt class="docutils literal"><span class="pre">onFailure</span></tt>, of which the latter two are specializations of the first.</p>
<div class="highlight-scala"><pre>future onSuccess {
  case "bar"     ⇒ println("Got my bar alright!")
  case x: String ⇒ println("Got some random string: " + x)
}
</pre>
</div>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">future</span> <span class="n">onFailure</span> <span class="o">{</span>
  <span class="k">case</span> <span class="n">ise</span><span class="k">:</span> <span class="kt">IllegalStateException</span> <span class="kt">if</span> <span class="kt">ise.getMessage</span> <span class="o">=</span><span class="k">=</span> <span class="s">&quot;OHNOES&quot;</span> <span class="k">⇒</span>
  <span class="c1">//OHNOES! We are in deep trouble, do something!</span>
  <span class="k">case</span> <span class="n">e</span><span class="k">:</span> <span class="kt">Exception</span> <span class="k">⇒</span>
  <span class="kt">//Do</span> <span class="kt">something</span> <span class="kt">else</span>
<span class="o">}</span>
</pre></div>
</div>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">future</span> <span class="n">onComplete</span> <span class="o">{</span>
  <span class="k">case</span> <span class="nc">Right</span><span class="o">(</span><span class="n">result</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">doSomethingOnSuccess</span><span class="o">(</span><span class="n">result</span><span class="o">)</span>
  <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">failure</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">doSomethingOnFailure</span><span class="o">(</span><span class="n">failure</span><span class="o">)</span>
<span class="o">}</span>
</pre></div>
</div>
</div>
<div class="section" id="define-ordering">
<h2>Define Ordering</h2>
<p>Since callbacks are executed in any order and potentially in parallel,
it can be tricky at the times when you need sequential ordering of operations.
But there&#8217;s a solution and it&#8217;s name is <tt class="docutils literal"><span class="pre">andThen</span></tt>. It creates a new <tt class="docutils literal"><span class="pre">Future</span></tt> with
the specified callback, a <tt class="docutils literal"><span class="pre">Future</span></tt> that will have the same result as the <tt class="docutils literal"><span class="pre">Future</span></tt> it&#8217;s called on,
which allows for ordering like in the following sample:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">result</span> <span class="k">=</span> <span class="nc">Future</span> <span class="o">{</span> <span class="n">loadPage</span><span class="o">(</span><span class="n">url</span><span class="o">)</span> <span class="o">}</span> <span class="n">andThen</span> <span class="o">{</span>
  <span class="k">case</span> <span class="nc">Left</span><span class="o">(</span><span class="n">exception</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">log</span><span class="o">(</span><span class="n">exception</span><span class="o">)</span>
<span class="o">}</span> <span class="n">andThen</span> <span class="o">{</span>
  <span class="k">case</span> <span class="k">_</span> <span class="k">⇒</span> <span class="n">watchSomeTV</span>
<span class="o">}</span>
</pre></div>
</div>
</div>
<div class="section" id="auxiliary-methods">
<h2>Auxiliary Methods</h2>
<p><tt class="docutils literal"><span class="pre">Future</span></tt> <tt class="docutils literal"><span class="pre">fallbackTo</span></tt> combines 2 Futures into a new <tt class="docutils literal"><span class="pre">Future</span></tt>, and will hold the successful value of the second <tt class="docutils literal"><span class="pre">Future</span></tt>
if the first <tt class="docutils literal"><span class="pre">Future</span></tt> fails.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">future4</span> <span class="k">=</span> <span class="n">future1</span> <span class="n">fallbackTo</span> <span class="n">future2</span> <span class="n">fallbackTo</span> <span class="n">future3</span>
</pre></div>
</div>
<p>You can also combine two Futures into a new <tt class="docutils literal"><span class="pre">Future</span></tt> that will hold a tuple of the two Futures successful results,
using the <tt class="docutils literal"><span class="pre">zip</span></tt> operation.</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">future3</span> <span class="k">=</span> <span class="n">future1</span> <span class="n">zip</span> <span class="n">future2</span> <span class="n">map</span> <span class="o">{</span> <span class="k">case</span> <span class="o">(</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="k">⇒</span> <span class="n">a</span> <span class="o">+</span> <span class="s">&quot; &quot;</span> <span class="o">+</span> <span class="n">b</span> <span class="o">}</span>
</pre></div>
</div>
</div>
<div class="section" id="exceptions">
<h2>Exceptions</h2>
<p>Since the result of a <tt class="docutils literal"><span class="pre">Future</span></tt> is created concurrently to the rest of the program, exceptions must be handled differently.
It doesn&#8217;t matter if an <tt class="docutils literal"><span class="pre">Actor</span></tt> or the dispatcher is completing the <tt class="docutils literal"><span class="pre">Future</span></tt>,
if an <tt class="docutils literal"><span class="pre">Exception</span></tt> is caught the <tt class="docutils literal"><span class="pre">Future</span></tt> will contain it instead of a valid result.
If a <tt class="docutils literal"><span class="pre">Future</span></tt> does contain an <tt class="docutils literal"><span class="pre">Exception</span></tt>, calling <tt class="docutils literal"><span class="pre">Await.result</span></tt> will cause it to be thrown again so it can be handled properly.</p>
<p>It is also possible to handle an <tt class="docutils literal"><span class="pre">Exception</span></tt> by returning a different result.
This is done with the <tt class="docutils literal"><span class="pre">recover</span></tt> method. For example:</p>
<div class="highlight-scala"><pre>val future = akka.pattern.ask(actor, msg1) recover {
  case e: ArithmeticException ⇒ 0
}
</pre>
</div>
<p>In this example, if the actor replied with a <tt class="docutils literal"><span class="pre">akka.actor.Status.Failure</span></tt> containing the <tt class="docutils literal"><span class="pre">ArithmeticException</span></tt>,
our <tt class="docutils literal"><span class="pre">Future</span></tt> would have a result of 0. The <tt class="docutils literal"><span class="pre">recover</span></tt> method works very similarly to the standard try/catch blocks,
so multiple <tt class="docutils literal"><span class="pre">Exception</span></tt>s can be handled in this manner, and if an <tt class="docutils literal"><span class="pre">Exception</span></tt> is not handled this way
it will behave as if we hadn&#8217;t used the <tt class="docutils literal"><span class="pre">recover</span></tt> method.</p>
<p>You can also use the <tt class="docutils literal"><span class="pre">recoverWith</span></tt> method, which has the same relationship to <tt class="docutils literal"><span class="pre">recover</span></tt> as <tt class="docutils literal"><span class="pre">flatMap</span></tt> has to <tt class="docutils literal"><span class="pre">map</span></tt>,
and is use like this:</p>
<div class="highlight-scala"><pre>val future = akka.pattern.ask(actor, msg1) recoverWith {
  case e: ArithmeticException        ⇒ Promise.successful(0)
  case foo: IllegalArgumentException ⇒ Promise.failed[Int](new IllegalStateException("All br0ken!"))
}
</pre>
</div>
</div>
</div>


          </div>
          <div class="span3"><p class="contents-title">Contents</p>
              <div id="scroller-anchor">
                <div id="scroller">
                  <div id="toc"></div>
                </div>
              </div></div>
        </div>
      </div>
    </div>
  </div>
  <div class="footer">
  <div class="container">
    <ul>
      <li><h5>Akka</h5></li>
      <li><a href="http://akka.io/docs">Documentation</a></li>
      <li><a href="http://akka.io/downloads">Downloads</a></li>
    </ul>
    <ul>
      <li><h5>Contribute</h5></li>
      <li><a href="http://github.com/akka/akka">Source Code</a></li>
      <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>      
      <li><a href="http://www.assembla.com/spaces/akka/tickets">Report a Bug</a></li>      
    </ul>
    <ul>
      <li><h5>Company</h5></li>
      <li><a href="http://typesafe.com/products/typesafe-subscription">Commercial Support</a></li>
      <li><a href="http://akka.io/team">Team</a></li>
      <li><a href="mailto:info@typesafe.com">Contact</a></li>
    </ul>
    <ul>
      <li><img src="../_static/watermark.png" align="center"/></li>
    </ul>
  </div>
  <div class="container copyright">
    <p style="float: left;">
      © 2012 <a href="http://typesafe.com/">Typesafe Inc.</a> <span class="license">Akka is Open Source and available under the Apache 2 License.</span>
    </p>
    <p style="float: right; font-size: 12px;">
      Last updated: Apr 13, 2012
    </p>          
  </div>
</div>
<script type="text/javascript">
  $('#toc').toc();
</script>
  

  </body>
</html>